package com.hb.trade.server.center.au.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.hb.core.pojo.center.au.dto.RoleDTO;
import com.hb.core.pojo.center.au.dto.UserApiDTO;
import com.hb.core.pojo.center.au.entity.ApiInfo;
import com.hb.core.pojo.center.au.entity.ApiRole;
import com.hb.core.pojo.center.au.entity.Role;
import com.hb.core.pojo.enums.ApiFilterType;
import com.hb.core.pojo.parent.MPBaseController;
import com.hb.core.util.URLUtil;
import com.hb.trade.server.center.au.service.ApiRoleService;
import com.hb.trade.server.center.au.service.RoleService;
import com.hb.trade.server.center.au.service.UserRoleService;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 角色关联中间表, 用于关联用户角色 前端控制器
 *
 * @author zhaojk
 * @since 2022-03-22
 */
@RestController
public class RoleApiController extends MPBaseController<ApiRole, ApiRoleService> {

    protected final RoleService roleService;
    protected final UserRoleService userRoleService;

    public RoleApiController(ApiRoleService service,
                             RoleService roleService,
                             UserRoleService userRoleService) {
        super(service);
        this.roleService = roleService;
        this.userRoleService = userRoleService;
    }

    @PostMapping("/au/checkAuth")
    public Message<Boolean> checkAuth(@RequestBody UserApiDTO userApiDTO) {
        Long userId = userApiDTO.getUserId();
        if (userId == null && userApiDTO.getRoleSignEnum() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }

        String apiName = userApiDTO.getApiName();
        if (StrUtil.isEmpty(apiName)) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }

        List<RoleDTO> roleDTOS;
        Role role = roleService.getRoleByRoleSign(userApiDTO.getRoleSignEnum());
        if (role == null) {
            roleDTOS = userRoleService.listRolesByUserId(userId);
        } else {
            roleDTOS = CollUtil.list(false);
            roleDTOS.add(role.to(RoleDTO.class));
        }

        List<Long> roleIds = CollUtil.map(roleDTOS, RoleDTO::getId, true);

        // 查询对应角色不允许访问的接口url
        List<ApiInfo> apis = service.listApisByRoleIds(roleIds, ApiFilterType.NOT_ALLOWED);
        if (CollUtil.isEmpty(apis)) {
            return MsgUtil.success(true);
        }

        for (ApiInfo api : apis) {
            if (URLUtil.matches(apiName, api.getApiName())) {
                return MsgUtil.success(false);
            }
        }
        return MsgUtil.success(true);
    }
}
